package com.uniview.listener;

import com.uniview.constants.QueueConstants;
import com.uniview.orm.model.ApiAuthority;
import com.uniview.service.listener.ScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;

import java.util.List;
import java.util.Map;

/**
 * @Author lux
 * @date: 2019/12/28
 * @desc: mq消息接收器
 */
@Slf4j
@Configuration
public class ResourceScanHandler {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ScanService scanService;

    private final static String SCAN_API_RESOURCE_KEY_PREFIX = "scan_api_resource:";

    /**
     * @param resource 接收的消息
     * @desc 接收API资源扫描消息
     */
    @RabbitListener(queues = QueueConstants.QUEUE_SCAN_API_RESOURCE)
    public void ScanApiResourceQueue(@Payload Map<String, Object> resource) {
        String serviceId = (String) resource.get("application");
        String key = SCAN_API_RESOURCE_KEY_PREFIX + serviceId;
        Object object = redisTemplate.opsForValue().get(key);
        if (object != null) {
            //3分钟内未失效,不再更新资源
            return;
        }
        //获取api相关权限信息
        List<Map<String,Object>> mappingList = (List<Map<String,Object>>)resource.get("mapping");
        for(Map<String,Object> mapping:mappingList){
            //查询数据库该api信息
            ApiAuthority apiAuthority = scanService.queryAuth(mapping);
            scanService.saveAuth(apiAuthority,mapping);
        }
    }
}
